<template>
  <section id="stats" class="stats-section" ref="statsSection">
    <div class="container">
      <div class="text-center mb-5" :class="{ 'slide-up visible': isVisible }">
        <h2 class="fw-bold">考研数据一览</h2>
        <p class="text-muted">基于全国1000+高校的实时数据分析</p>
      </div>
      <div class="row">
        <div
            v-for="(stat, index) in stats"
            :key="stat.title"
            class="col-md-3 col-6 stat-item"
            :class="{ 'slide-up visible': isVisible }"
            :style="{ transitionDelay: `${index * 0.2}s` }"
        >
          <div class="stat-number">{{ animatedStats[stat.title] }}</div>
          <h5>{{ stat.title }}</h5>
          <small v-if="stat.unit">{{ stat.unit }}</small>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'StatsSection',
  data() {
    return {
      stats: [
        { title: '合作院校', value: 1286, unit: '' },
        { title: '录取数据', value: 356000, unit: '' },
        { title: '专业覆盖率', value: 98, unit: '%' },
        { title: '服务用户', value: 150000, unit: '' }
      ],
      animatedStats: {
        '合作院校': 0,
        '录取数据': 0,
        '专业覆盖率': 0,
        '服务用户': 0
      },
      isVisible: false
    }
  },
  methods: {
    animateNumbers() {
      this.stats.forEach(stat => {
        const duration = 2000
        const start = 0
        const increment = stat.value / (duration / 16)
        let current = start

        const timer = setInterval(() => {
          current += increment
          if (current >= stat.value) {
            clearInterval(timer)
            current = stat.value
          }
          this.$set(this.animatedStats, stat.title, Math.floor(current).toLocaleString())
        }, 16)
      })
    },
    checkVisibility() {
      if (this.$refs.statsSection) {
        const elementTop = this.$refs.statsSection.getBoundingClientRect().top
        const windowHeight = window.innerHeight
        if (elementTop < windowHeight - 100) {
          this.isVisible = true
          this.animateNumbers()
          window.removeEventListener('scroll', this.checkVisibility)
        }
      }
    }
  },
  mounted() {
    window.addEventListener('scroll', this.checkVisibility)
    this.checkVisibility()
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.checkVisibility)
  }
}
</script>

<style scoped>
.stats-section {
  padding: 80px 0;
  background-color: white;
}

.stat-item {
  text-align: center;
  padding: 30px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  transform: translateY(-10px);
}

.stat-number {
  font-size: 48px;
  font-weight: bold;
  color: var(--primary-color);
  margin-bottom: 15px;
}

.slide-up {
  opacity: 0;
  transform: translateY(50px);
  transition: all 0.6s ease-out;
}

.slide-up.visible {
  opacity: 1;
  transform: translateY(0);
}

@media (max-width: 768px) {
  .stat-number {
    font-size: 36px;
  }
}
</style>